#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/6/25 21:46
# @Author  : LiShan
# @Email   : lishan_1997@126.com
# @File    : pre_process.py
# @Note    : this is note

import os
import cv2.cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
# np.set_printoptions(threshold=np.inf)

save_path = "./pre_process"
img_path = "./picture/338.jpg"
width = 480
height = 360

if os.path.exists(save_path):
    pass
else:
    os.mkdir(save_path)

'''   自适应中值滤波器的python实现   '''
def AdaptProcess(src, i, j, minSize, maxSize):
    filter_size = minSize
    kernelSize = filter_size // 2
    rio = src[i-kernelSize:i+kernelSize+1, j-kernelSize:j+kernelSize+1]
    minPix = np.min(rio)
    maxPix = np.max(rio)
    medPix = np.median(rio)
    zxy = src[i,j]

    if (medPix > minPix) and (medPix < maxPix):
        if (zxy > minPix) and (zxy < maxPix):
            return zxy
        else:
            return medPix
    else:
        filter_size = filter_size + 2
        if filter_size <= maxSize:
            return AdaptProcess(src, i, j, filter_size, maxSize)
        else:
            return medPix


def adapt_meadian_filter(img, minsize, maxsize):
    borderSize = maxsize // 2
    src = cv.copyMakeBorder(img, borderSize, borderSize, borderSize, borderSize, cv.BORDER_REFLECT)
    for m in range(borderSize, src.shape[0] - borderSize):
        for n in range(borderSize, src.shape[1] - borderSize):
            src[m,n] = AdaptProcess(src, m, n, minsize, maxsize)
    dst = src[borderSize:borderSize+img.shape[0], borderSize:borderSize+img.shape[1]]
    return dst






def pre_process(img):
    img = cv.resize(img, (width, height))
    # 原图
    origin = img
    cv.imwrite(save_path + "/origin.jpg", origin)
    # cv.imshow("origin", origin)


    # 转为灰度图
    gray = cv.cvtColor(origin, cv.COLOR_BGR2GRAY)
    cv.imwrite(save_path + "/gray.jpg", gray)
    # cv.imshow("gray", gray)

    # 中值滤波
    # median = cv.medianBlur(fgmask, 5)

    # 自适应中值滤波
    # fil = adapt_meadian_filter(gray, 1, 5)
    # cv.imshow("filter", fil)

    # 直方图均衡化
    # equ = cv.equalizeHist(gray)
    # res = np.hstack((filter, equ))
    # stacking images side-by-side
    # cv.imshow('equ', equ)

    # 二值化
    # ret, Binary = cv.threshold(gray, 50, 255, cv.THRESH_BINARY)

    # 边缘检测
    edge = cv.Canny(gray, 50, 150, apertureSize=3)
    cv.imwrite(save_path + "/edge50-150.jpg", edge)

    edge = cv.Canny(gray, 100, 150, apertureSize=3)
    cv.imwrite(save_path + "/edge100-150.jpg", edge)
    # cv.imshow("edges", edge)

    # plt.subplot(131)
    # plt.imshow(cv.cvtColor(origin, cv.COLOR_BGR2RGB))
    # plt.axis("off")
    #
    # plt.subplot(132)
    # plt.imshow(cv.cvtColor(gray, cv.COLOR_BGR2RGB))
    # plt.axis("off")
    #
    # plt.subplot(133)
    # plt.imshow(cv.cvtColor(edge, cv.COLOR_BGR2RGB))
    # plt.axis("off")
    #
    # plt.savefig("pre.jpg", dpi=600)
    # plt.show()

    # # 中值滤波
    # median = cv.medianBlur(gray, 5)
    # # cv.imshow("median", median)
    # # 形态学操作
    # element = cv.getStructuringElement(cv.MORPH_RECT, (1, 1))
    # element2 = cv.getStructuringElement(cv.MORPH_RECT, (1, 1))
    # # 开运算
    # image = cv.morphologyEx(median, cv.MORPH_OPEN, element)
    # # 膨胀运算
    # morphology = cv.dilate(image, element2)
    # # cv.imshow('morphology', morphology)
    # # 二值图像提取轮廓，轮廓跟踪算法（Suzuki，1985）
    # contours, hierarchy = cv.findContours(morphology, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)




if __name__ == '__main__':
    # 窗口排列
    # cv.namedWindow("origin", 0)
    # cv.resizeWindow("origin", width, height)
    # cv.moveWindow("origin", 0, 0)
    #
    # cv.namedWindow("gray", 0)
    # cv.resizeWindow("gray", width, height)
    # cv.moveWindow("gray", width * 1, 0)
    #
    # cv.namedWindow("edges", 0)
    # cv.resizeWindow("edges", width, height)
    # cv.moveWindow("edges", width * 2, 0)
    #
    # cv.namedWindow("median", 0)
    # cv.resizeWindow("median", width, height)
    # cv.moveWindow("median", width * 0, 30 + height * 1)
    #
    # cv.namedWindow("morphology", 0)
    # cv.resizeWindow("morphology", width, height)
    # cv.moveWindow("morphology", width * 1, 30 + height * 1)
    #
    # cv.namedWindow("Contours", 0)
    # cv.resizeWindow("Contours", width, height)
    # cv.moveWindow("Contours", width * 2, 30 + height * 1)
    if os.path.exists(img_path):
        img = cv.imread(img_path)
        flag = True
    else:
        print("图片不存在")
        img = np.zeros(width, height)
        flag = False
    if flag:
        pre_process(img)
        key = cv.waitKey() & 0xFF
        if key == ord("q"):
            flag = False
    cv.destroyAllWindows()
